package cn.tedu.boot61.controller;

import cn.tedu.boot61.entity.Image;
import cn.tedu.boot61.mapper.ImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class ImageController {
    @Autowired(required = false)
    ImageMapper mapper;

    @RequestMapping("/insert")
    public void insert(Image image, MultipartFile picFile) throws IOException {
        System.out.println("image = "+image + ",picFile=" + picFile);
        //得到图片的原始文件名
        String fileName = picFile.getOriginalFilename();
        //得到文件的后缀 abc.jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到一个唯一的文件名
        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);
        String dirPath = "D:/upload";
        File dirFile = new File(dirPath);
        //
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath+"/"+fileName;
        //把接收到的文件保存到上面的路径
        picFile.transferTo(new File(filePath));
        //把图片的路径添加到实体类中
        image.setUrl("/"+fileName);
        //把图片的信息保存到数据库里面
        mapper.insert(image);
    }

    @RequestMapping("/select")
    public List<Image> select(){
        return mapper.select();
    }


}
